<script lang="ts">
export default { name: 'ContentForm' }
</script>

<script setup lang="ts">
import { computed, ref, toRefs, watch, nextTick, PropType } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Finished,
  Box,
  Promotion,
  DocumentRemove,
  Delete,
  CircleCheck,
  CircleClose,
  ArrowDownBold,
  View
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'
import {
  getContentApi,
  createContentApi,
  createPreviewContentApi,
  updateContentApi,
  submitContentApi,
  getConvertEnabledApi,
  getPublishMultiChannelEnabledApi,
  approveContentApi,
  rejectContentApi,
  archiveContentApi,
  offlineContentApi,
  publishContentApi,
  deleteContentApi,
  twoDeleteContentApi,
  checkSensitiveWordApi
} from '@/api/cms/content'
import {checkEasyErrorWordApi} from '@/api/cms/sysWord'
import { docUploadUrl, docImportUrl } from '@/api/cms/upload/types'
import { getDictDictTypeAndNameLike } from '@/utils/dict'
import { getContentChannelTreeApi, getChannelApi } from '@/api/cms/channel'
import { getModelList } from '@/api/cms/model'
import { getChannelTpl } from '@/api/cms/tpl'
import { toTree } from '@/utils/cmstree'
import { formatDuration } from '@/utils/cmscommon'
import { getModelData, mergeModelFields, arr2obj } from '@/utils/cmscommon'

import FieldItem from '@/views/cms/setting/cmsmodel/component/FieldItem.vue'
import LabelTip from '@/components/cms/LabelTip.vue'
import DialogForm from '@/components/cms/DialogForm.vue'
import { BaseUpload, ImageUpload, ImageListUpload, FileListUpload } from '@/components/cms/upload'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { otherSettings, initConfig } from '@/store/modules/cmsGlobalConfig'
import { useUserStore } from '@/store/modules/user'
import * as TaskApi from '@/api/bpm/task'
import { checkPermi } from '@/utils/permission'
const message = useMessage() // 消息弹窗
const props = defineProps({
  modelValue: { type: Boolean, required: true },
  beanId: { type: Number, default: null },
  action: { type: String as PropType<'add' | 'copy' |'review'| 'edit'>, default: 'edit' },
  channel: { type: Object, default: null },
  review: { type: Boolean, default: false }
})
defineEmits({ 'update:modelValue': null, finished: null })

const { modelValue: visible, channel, beanId } = toRefs(props)
const { t } = useI18n()
const dialog = ref<any>()
const displaySubtitle = ref<boolean>(false)
const displayOutLink = ref<boolean>(false)
const focus = ref<any>()
const values = ref<any>({
  topLevel: 0,
  downRemoteImage:true
})
const converterEnabled = ref<boolean>(false)
const publishMultiChannelEnabled = ref<boolean>(false)
const channelList = ref<any[]>([])
const flatChannelList = ref<any[]>([])
const contentModelList = ref<any[]>([])
const contentModelId = ref<number>()
const contentPcTemplates = ref<any[]>([])
const contentH5Templates = ref<any[]>([])
const contentModel = computed(() => {
  if (contentModelId.value != null) {
    return contentModelList.value.find((item) => item.id === contentModelId.value)
  }
  return contentModelList.value[0]
})
const processTask = ref<any>()
const mainFields = computed(() => {
  const rs = arr2obj(
    mergeModelFields(getModelData().content.mainFields, contentModel.value?.mainFields, 'content')
  )
  return rs
})
const rightFields = computed(() =>
  arr2obj(
    mergeModelFields(getModelData().content.rightFields, contentModel.value?.rightFields, 'content')
  )
)
//自定义字段排除掉富文本
const customFields = computed(() =>
  JSON.parse(contentModel.value?.customs || '[]').filter((item: any) => item.type !== 'editor')
)
//自定义字段中富文本
const editorFields = computed(() =>
  JSON.parse(contentModel.value?.customs || '[]').filter((item: any) => item.type === 'editor')
)

watch(visible, async () => {
  if (visible.value) {
    getConverterEnabled()
    getPublishMultiChannelEnabled()
    //先获取栏目
    getChannelList()
    //取模板需要先拿到modelId 拿到 模型之后自取设置 contentModelId
    await getContentModeList().then(() => {
      getContentH5Templates()
      getContentPcTemplates()
    })
    //查询我的待审核
    getProcessTask()
    //查询栏目的工作流信息
    getChannelUseProcessDefinitionId()
  }
})
//是否开启文档转换
const getConverterEnabled = async () => {
  converterEnabled.value = await getConvertEnabledApi()
}
//是否开启引用多栏目功能
const getPublishMultiChannelEnabled = async () => {
  publishMultiChannelEnabled.value = await getPublishMultiChannelEnabledApi()
}
//来源来自字典类型 sys_content_source
const getSourceList = (name: string) => getDictDictTypeAndNameLike('sys_content_source', name)
//左侧栏目列表
const getChannelList = async () => {
  flatChannelList.value = await getContentChannelTreeApi()
  channelList.value = toTree(flatChannelList.value)
}
//内容模型
const getContentModeList = async () => {
  contentModelList.value = await getModelList(2)
  // 如果 contentModelId 无值，则默认赋予第一个模型的值
  if (contentModelId.value == null && contentModelList.value.length > 0) {
    contentModelId.value = contentModelList.value[0].id
  }
}
//内容模型可用pc模板
const getContentPcTemplates = async () => {
  contentPcTemplates.value = await getChannelTpl(true, contentModelId?.value)
}
//内容模型可用h5模板
const getContentH5Templates = async () => {
  contentH5Templates.value = await getChannelTpl(false, contentModelId?.value)
}
//获取我的待审核任务
const getProcessTask = async () => {
  if (beanId.value) {
    const content = await getContentApi(beanId.value)
    if(content.processInstanceId){
      processTask.value = await TaskApi.getLastTaskByProcessInstanceId(content.processInstanceId)
     }
   }
}
//获取栏目使用的工作流
const channelUseProcessDefinitionId = ref('')
const getChannelUseProcessDefinitionId = async () => {
  if (values.value.channelId) {
    const targetChannel = await getChannelApi(values.value.channelId)
    channelUseProcessDefinitionId.value = targetChannel.useProcessDefinitionId
  }
}
const contentMarks = ref()
const contentBlocks = ref()
const init = () => {
  contentMarks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_MARKS)
  contentBlocks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_BLOCKS)
}
const initCustoms = (customs: any) => {
  customFields.value.forEach((field: any) => {
    if (customs[field.code] == null) {
      customs[field.code] = field.defaultValue
      if (field.defaultValueKey != null) {
        customs[field.code + '_cus'] = field.defaultValueKey
      }
    }
  })
  return customs
}

const handleSaveToDraft = () => {
  dialog.value.submit(
    async (
      values: any,
      { focus, emit, props, form }: { focus: any; emit: any; props: any; form: any }
    ) => {
      // 草稿
      values.status = 6
      if(beanId.value){
        await updateContentApi(values)
      }else{
        await createContentApi(values)
      }
      focus?.focus?.()
      emit('update:values', props.initValues(values.value))
      form.resetFields()
      ElMessage.success(t('common.success'))
    }
  )
}
const handleLivePreview = () => {
  dialog.value.submit(
    async (
      values: any,
      { focus, emit, props, form }: { focus: any; emit: any; props: any; form: any }
    ) => {
      // 草稿
      values.status = 6
      const contentId = await createPreviewContentApi(values)
      focus?.focus?.()
      emit('update:values', props.initValues(values.value))
      form.resetFields()
      const content = await getContentApi(contentId)
      const url = content.livePreviewUrl
      if (url) window.open(url, '_blank')
    }
  )
}
const handleExecute = async (action: string, id: number) => {
  if (['approve', 'reject'].includes(action)) {
    dialog.value.remove(async (values: any) => {
      //审核通过
      if (action === 'approve') {
        try {
          const { value } = await ElMessageBox.prompt(
            t('cms.content.approve.reason'),
            t('common.approve'),
            {
              confirmButtonText: t('common.submit'),
              cancelButtonText: t('common.cancel'),
              inputPattern: /\S+/,
              inputErrorMessage: t('common.required')
            }
          )
          await approveContentApi({ id: id, taskId: processTask.value.id, reason: value })
        } catch (e) {
          /* empty */
        }
      } else if (action === 'reject') {
        //不通过
        try {
          const { value } = await ElMessageBox.prompt(
            t('cms.content.reject.reason'),
            t('common.reject'),
            {
              confirmButtonText: t('common.submit'),
              cancelButtonText: t('common.cancel'),
              inputPattern: /\S+/,
              inputErrorMessage: t('common.required')
            }
          )
          await rejectContentApi({ id: id, taskId: processTask.value.id, reason: value })
        } catch (e) {
          /* empty */
        }
      }
    })
    return
  }

  //其他动作 删除 提交审核 下线 归档
  dialog.value.submit(async (values: any, { loadBean }: { loadBean: () => Promise<any> }) => {
    if (action === 'delete') {
      await deleteContentApi([id])
    } else if (action === 'submit') {
      await submitContentApi(id)
    } else if (action === 'archive') {
      await archiveContentApi([id])
    } else if (action === 'offline') {
      await offlineContentApi([id])
    } else if (action === 'publish') {
      await publishContentApi([id])
    } else {
      throw new Error(`not support action: ${action}`)
    }
    loadBean()
  })
}
const checkSensitiveWord = async (text: String,key:String) => {
  //先检查易错词
  if (text&&text.trim()) {
    const easyErrorWords = await checkEasyErrorWordApi({ text: text.trim() })
    if (easyErrorWords&&easyErrorWords.length > 0) {
      const words = easyErrorWords.map(item => item.word);
      const data = await message.confirmCusBtnTxt(`存在可疑易错词${words}!`, t('common.reminder'),t('cms.content.op.replace'),t('cms.content.op.ignore'))
      if (data == 'confirm') {
        //替换
        for (const easyErrorWord of easyErrorWords) {  
          values.value[key] = values.value[key].replaceAll(easyErrorWord.word,easyErrorWord.replaceWord)
        }
      }
    }
  }
  //0:不提示直接替换; 1:提示之后替换; 2:不允许提交;3 关闭敏感词)
  if (
    otherSettings.sensitiveWordProcessModel == 0 ||
    otherSettings.sensitiveWordProcessModel == 3
  ) {
    return
  }
  if (text&&text.trim()) {
    const sensitiveWords = await checkSensitiveWordApi({ text: text.trim() })
    if (sensitiveWords.length > 0) {
      message.error(`存在敏感词${sensitiveWords}!`)
    }
  }
}
const handleTxtBlur = async (text: String,key:String) => {
  // const text = editor.getText()
  await checkSensitiveWord(text,key)
}
// ========== 初始化 ==========
onMounted(() => {
  //初始化字段信息
  init()
  //获取系统全局配置
  initConfig()
})
</script>

<template>
  <div>
    <dialog-form
      ref="dialog"
      v-model:values="values"
      :name="t('cms.menu.content')"
      :query-func="getContentApi"
      :create-func="createContentApi"
      :update-func="updateContentApi"
      :delete-func="twoDeleteContentApi"
      :bean-id="beanId"
      :action="action"
      :focus="focus"
      :init-values="
        () => ({
          editorType: mainFields['text'].editorType,
          channelId: channel?.id,
          customs: initCustoms({}),
          attachs: [],
          images: [],
          topLevel: 0,
          downRemoteImage:true
        })
      "
      :to-values="(bean) => ({ ...bean })"
      perms="content"
      :model-value="modelValue"
      :addable="!review"
      :disable-edit="(bean) => bean.id != null && !bean.editable"
      label-width="140px"
      large
      @update:model-value="(event) => $emit('update:modelValue', event)"
      @finished="() => $emit('finished')"
      @bean-change="
        (bean) => {
          displaySubtitle = !!bean.subtitle
          displayOutLink = !!bean.outLink
          contentModelId = bean.modelId ? bean.modelId : channel?.contentModelId
        }
      "
    >
      <template #header-action="{ isEdit, bean, unsaved, handleDelete }">
        <!-- 审核按钮 -->
        <el-button-group v-if="review">
          <el-popconfirm
            :title="t('common.confirmApprove')"
            @confirm="() => handleExecute('approve', bean.id)"
          >
            <template #reference>
              <el-button v-hasPermi="['cms:content:approve']" type="primary" :icon="CircleCheck">{{
                t('common.approve')
              }}</el-button>
            </template>
          </el-popconfirm>
          <el-button
            v-hasPermi="['cms:content:reject']"
            :icon="CircleClose"
            @click="() => handleExecute('reject', bean.id)"
            >{{ t('common.reject') }}</el-button
          >
        </el-button-group>
        <!-- 一般按钮 -->
        <el-button-group v-if="!review">
          <el-popconfirm
            v-if="isEdit"
            :title="t('common.confirmAction')"
            @confirm="() => handleExecute('submit', bean.id)"
          >
            <template #reference>
              <el-button
                v-hasPermi="['cms:content:submit']"
                :disabled="[2].includes(bean.status) || unsaved ||([1].includes(bean.status)&&!bean.editPublishContentToSubmit)"
                :icon="Finished"
                >{{ t('cms.content.op.submit') }}</el-button
              >
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="isEdit"
            :title="t('common.confirmAction')"
            @confirm="() => handleExecute('archive', bean.id)"
          >
            <template #reference>
              <el-button
                v-hasPermi="['cms:content:archive']"
                :disabled="![1].includes(bean.status) || unsaved"
                :icon="Box"
                >{{ t('cms.content.op.archive') }}</el-button
              >
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="isEdit"
            :title="t('common.confirmAction')"
            @confirm="() => handleExecute('publish', bean.id)"
          >
            <template #reference>
              <el-button
                v-hasPermi="['cms:content:publish']"
                :disabled="[2].includes(bean.status) || bean.processDefinitionId || unsaved"
                :icon="Promotion"
                >{{
                  bean.status == 1 ? t('cms.content.op.republish') : t('cms.content.op.publish')
                }}</el-button
              >
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="isEdit"
            :title="t('common.confirmAction')"
            @confirm="() => handleExecute('offline', bean.id)"
          >
            <template #reference>
              <el-button
                v-hasPermi="['cms:content:offline']"
                :disabled="![1].includes(bean.status) || unsaved"
                :icon="ArrowDownBold"
                >{{ t('cms.content.op.offline') }}</el-button
              >
            </template>
          </el-popconfirm>
        </el-button-group>
        <!-- 删除按钮 -->
        <el-button-group>
          <el-popconfirm
            v-if="isEdit && !review"
            :title="t('confirmDelete')"
            @confirm="() => handleDelete()"
          >
            <template #reference>
              <el-button v-hasPermi="['cms:content:delete']" :icon="DocumentRemove">{{
                t('cms.content.op.delete')
              }}</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            v-if="isEdit"
            :title="t('common.confirmTwoDelete')"
            @confirm="() => handleDelete()"
          >
            <template #reference>
              <el-button v-hasPermi="['cms:content:delete']" :icon="Delete">{{
                t('cms.content.op.twoDelete')
              }}</el-button>
            </template>
          </el-popconfirm>
        </el-button-group>
        <el-button :icon="View" @click="handleLivePreview()">{{
          t('cms.content.op.livepreview')
        }}</el-button>
      </template>
      <template #header-status="{ isEdit }">
        <template v-if="isEdit">
          <span v-if="values.status != null">
            <el-tag v-if="values.status === 1" type="success" size="small" disable-transitions>{{
              t(`cms.content.status.${values.status}`)
            }}</el-tag>
            <el-tag v-else-if="values.status === 9" size="small" disable-transitions>{{
              t(`cms.content.status.${values.status}`)
            }}</el-tag>
            <el-tag
              v-else-if="values.status === 7"
              type="danger"
              size="small"
              disable-transitions
              >{{ t(`cms.content.status.${values.status}`) }}</el-tag
            >
            <el-tag
              v-else-if="values.status === 5"
              type="warning"
              size="small"
              disable-transitions
              >{{ t(`cms.content.status.${values.status}`) }}</el-tag
            >
            <el-tag v-else type="info" size="small" disable-transitions>{{
              t(`cms.content.status.${values.status}`)
            }}</el-tag>
          </span>
        </template>
      </template>
      <template #default="{ bean, isEdit, disabled }">
        <el-row>
          <!-- 编辑主区域 -->
          <el-col :span="18">
            <el-row>
              <el-col v-if="values.originContentId" :span="mainFields['title'].double ? 12 : 24">
                <el-form-item :label="t('cms.content.originContent')">
                  <el-input :model-value="values.originContent.title" disabled>
                    <template #prepend>{{ t(`cms.content.type.${values.createMode}`) }}</template>
                    <template #append>{{
                      values.originContent.nodeNames.map((name: string) => name).join('>')
                    }}</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="mainFields['title'].double ? 12 : 24">
                <el-form-item
                  prop="title"
                  :label="mainFields['title'].name ?? t('cms.content.title')"
                  :rules="{ required: true, message: () => t('common.required') }"
                >
                  <el-input
                    ref="focus"
                    v-model="values.title"
                    maxlength="150"
                    @blur="checkSensitiveWord(values.title,'title')"
                  >
                    <template
                      v-if="
                        (!mainFields['subtitle'].required || !mainFields['outLink'].required) &&
                        (mainFields['subtitle'].show || mainFields['outLink'].show)
                      "
                      #append
                    >
                      <el-checkbox v-model="values.titleBold" class="pr-5">{{
                        t('cms.content.bold')
                      }}</el-checkbox>
                      <el-button
                        v-if="mainFields['subtitle'].show && !mainFields['subtitle'].required"
                        :class="displaySubtitle ? 'text-primary' : undefined"
                        @click="
                          () => {
                            displaySubtitle = !displaySubtitle
                            values.subtitle = undefined
                          }
                        " style="margin-right:10px"
                        >{{ mainFields['subtitle'].name ?? t('cms.content.subtitle') }}
                      </el-button>
                      <el-button
                        v-if="mainFields['outLink'].show && !mainFields['outLink'].required"
                        :class="() => (displayOutLink ? 'text-primary' : undefined)"
                        :disabled="values.originContent != null && values.createMode === 3"
                        @click="
                          () => {
                            displayOutLink = !displayOutLink
                            values.outLink = undefined
                            values.targetBlank = false
                          }
                        " 
                        >{{ mainFields['outLink'].name ?? t('cms.content.outLink') }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                v-if="
                  ((values.subtitle || displaySubtitle) && mainFields['subtitle'].show) ||
                  (mainFields['subtitle'].show && mainFields['subtitle'].required)
                "
                :span="mainFields['subtitle'].double ? 12 : 24"
              >
                <el-form-item
                  prop="subtitle"
                  :label="mainFields['subtitle'].name ?? t('cms.content.subtitle')"
                  :rules="
                    mainFields['subtitle'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-input
                    v-model="values.subtitle"
                    maxlength="150"
                    @blur="checkSensitiveWord(values.subtitle,'subtitle')"
                  >
                  <template #append>
                    <el-checkbox v-model="values.subtitleBold">{{
                          t('cms.content.bold')
                        }}</el-checkbox>
                      </template>
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col
                v-if="
                  ((values.outLink || displayOutLink) && mainFields['outLink'].show) ||
                  (mainFields['outLink'].show && mainFields['outLink'].required)
                "
                :span="mainFields['outLink'].double ? 12 : 24"
              >
                <el-form-item
                  prop="outLink"
                  :label="mainFields['outLink'].name ?? t('cms.content.outLink')"
                  :rules="
                    mainFields['outLink'].required
                      ? [
                          { required: true, message: () => t('common.required') },
                          {
                            pattern: /^(http|\/).*$/,
                            message: () => t('cms.content.error.outLink')
                          }
                        ]
                      : { pattern: /^(http|\/).*$/, message: () => t('cms.content.error.outLink') }
                  "
                >
                  <el-input
                    v-model="values.outLink"
                    maxlength="255"
                    :disabled="values.originContent != null && values.createMode === 3"
                  >
                    <template #append>
                      <el-checkbox v-model="values.targetBlank">{{
                        t('cms.content.targetBlank')
                      }}</el-checkbox>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['tagsNames'].show"
                :span="mainFields['tagsNames'].double ? 12 : 24"
              >
                <el-form-item
                  prop="tags"
                  :label="mainFields['tagsNames'].name ?? t('cms.content.tagsNames')"
                  :rules="
                    mainFields['tagsNames'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-input v-model="values.tagNames" maxlength="150" />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['keywords'].show"
                :span="mainFields['keywords'].double ? 12 : 24"
              >
                <el-form-item
                  prop="keywords"
                  :label="mainFields['keywords'].name ?? t('cms.content.keywords')"
                  :rules="
                    mainFields['keywords'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-input v-model="values.keywords" maxlength="150" />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['description'].show"
                :span="mainFields['description'].double ? 12 : 24"
              >
                <el-form-item
                  prop="description"
                  :label="mainFields['description'].name ?? t('cms.content.description')"
                  :rules="
                    mainFields['description'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-input
                    v-model="values.description"
                    type="textarea"
                    :rows="3"
                    maxlength="1000"
                    @blur="checkSensitiveWord(values.description,'description')"
                  />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['author'].show"
                :span="mainFields['author'].double ? 12 : 24"
              >
                <el-form-item
                  prop="author"
                  :label="mainFields['author'].name ?? t('cms.content.author')"
                  :rules="
                    mainFields['author'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-input
                    v-model="values.author"
                    maxlength="50"
                    @blur="checkSensitiveWord(values.author,'author')"
                  />
                </el-form-item>
              </el-col>
              <el-col v-if="mainFields['text'].show" :span="mainFields['text'].double ? 12 : 24">
                <el-form-item
                  prop="text"
                  :label="mainFields['text'].name ?? t('cms.content.text')"
                  :rules="
                    mainFields['text'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <div class="w-full">
                    <span v-if="converterEnabled" class="inline-flex mb-1">
                      <base-upload
                        type="doc"
                        v-hasPermi="['cms:content:docImport']"
                        :upload-action="docImportUrl"
                        :on-success="(res: string) => (values.text = res.data)"
                        :button="t('cms.content.op.docImport')"
                      />
                    </span>
                    <span>
                      <el-switch
                      :inactive-text="t('cms.content.op.downRemoteImage')"   v-model="values.downRemoteImage" />
                    </span>
                    <div class="contentEditor">
                      <Editor v-if="mainFields['text'].editorType ===1" v-model="values.text" />
                      <TinymceEditor v-else-if="mainFields['text'].editorType ===2"  v-model="values.text" />
                      <UEditor v-else v-model="values.text" />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['sysImage'].show"
                :span="mainFields['sysImage'].double ? 12 : 24"
              >
                <el-form-item
                  prop="sysImage"
                  :label="mainFields['sysImage'].name ?? t('cms.content.sysImage')"
                  :rules="
                    mainFields['sysImage'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <image-upload
                    v-model="values.sysImage"
                    :height="mainFields['sysImage'].imageHeight"
                    :width="mainFields['sysImage'].imageWidth"
                    :mode="mainFields['sysImage'].imageMode"
                    :disabled="disabled"
                  />
                </el-form-item>
              </el-col>
              <template v-for="field in customFields" :key="field.code">
                <el-col :span="field.double ? 12 : 24">
                  <el-form-item
                    :prop="`customs.${field.code}`"
                    :rules="
                      field.required
                        ? { required: true, message: () => t('common.required') }
                        : undefined
                    "
                  >
                    <template #label><label-tip :label="field.name" /></template>
                    <field-item
                      v-model="values.customs[field.code]"
                      v-model:model-key="values.customs[field.code + '_cus']"
                      :field="field"
                      @input-blur="handleTxtBlur"
                    />
                  </el-form-item>
                </el-col>
              </template>
              <el-col
                v-if="mainFields['sysAttach'].show"
                :span="mainFields['sysAttach'].double ? 12 : 24"
              >
                <el-form-item
                  prop="sysAttach"
                  :label="mainFields['sysAttach'].name ?? t('cms.content.sysAttach')"
                  :rules="
                    mainFields['sysAttach'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-row class="w-full">
                    <el-col :span="16">
                      <el-input v-model="values.sysAttachName">
                        <template #prepend>{{ $t('cms.content.sysAttach.name') }}</template>
                      </el-input>
                    </el-col>
                    <el-col :span="8">
                      <el-input v-model="values.sysAttachFileSize">
                        <template #prepend>{{ $t('cms.content.sysAttach.fileSize') }}</template>
                        <template #append>Byte</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <el-input v-model="values.sysAttach">
                    <template #prepend>URL</template>
                  </el-input>
                  <base-upload
                    type="file"
                    :on-success="
                      (res: any) => (
                        (values.sysAttach = res.data.url),
                        (values.sysAttachName = res.data.name),
                        (values.sysAttachFileSize = res.data.size)
                      )
                    "
                    :disabled="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['sysVideo'].show"
                :span="mainFields['sysVideo'].double ? 12 : 24"
              >
                <el-form-item
                  prop="sysVideo"
                  :label="mainFields['sysVideo'].name ?? t('cms.content.sysVideo')"
                  :rules="
                    mainFields['sysVideo'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-row class="w-full">
                    <el-col :span="16">
                      <el-input v-model="values.sysVideo" maxlength="255">
                        <template #prepend>URL</template>
                      </el-input>
                    </el-col>
                    <el-col :span="8">
                      <el-input v-model="values.sysVideoDuration" maxlength="10">
                        <template #prepend>{{ t('cms.content.sysVideoDuration') }}</template>
                        <template #append> {{ formatDuration(values.sysVideoDuration) }}</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <base-upload
                    type="video"
                    :on-success="
                      (res) => {
                        values.sysVideo = res.data.url
                        values.sysVideoDuration = res.data.duration
                        //视频截取图
                        if (!values.sysImage) {
                          values.sysImage = res.data.image
                        }
                      }
                    "
                    :disabled="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['sysAudio'].show"
                :span="mainFields['sysAudio'].double ? 12 : 24"
              >
                <el-form-item
                  prop="sysAudio"
                  :label="mainFields['sysAudio'].name ?? t('cms.content.sysAudio')"
                  :rules="
                    mainFields['sysAudio'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-row class="w-full">
                    <el-col :span="24">
                      <el-input v-model="values.sysAudio" maxlength="255">
                        <template #prepend>URL</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <base-upload
                    type="audio"
                    :on-success="
                      (res) => {
                        values.sysAudio = res.data.url
                      }
                    "
                    :disabled="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['docPdf'].show"
                :span="mainFields['docPdf'].double ? 12 : 24"
              >
                <el-form-item
                  v-if="useUserStore().grade >= 1"
                  prop="docPdf"
                  :label="mainFields['docPdf'].name ?? t('cms.content.docPdf')"
                  :rules="
                    mainFields['docPdf'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <div class="w-full">
                    <el-row>
                      <el-col :span="24">
                        <el-input v-model="values.docName">
                          <template #prepend>{{ t('cms.content.docName') }}</template>
                        </el-input>
                      </el-col>
                    </el-row>
                    <el-input v-model="values.docPdf">
                      <template #prepend>URL</template>
                    </el-input>
                    <el-input v-model="values.originDoc">
                      <template #prepend>{{ t('cms.content.originDoc') }}</template>
                    </el-input>
                    <base-upload
                      v-if="converterEnabled"
                      type="library"
                      v-hasPermi="['cms:content:convertLibrary']"
                      :upload-action="docUploadUrl"
                      :on-success="
                        (res: any) => {
                          values.docPdf = res.data.docPdf
                          values.originDoc = res.data.originDoc
                          values.docName = res.data.docName
                          values.sysImage = res.data.docImage
                        }
                      "
                    />
                    <el-alert
                      v-if="!converterEnabled"
                      :title="t('cms.error.converterNotEnabled')"
                      type="error"
                      :closable="false"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['images'].show"
                :span="mainFields['images'].double ? 12 : 24"
              >
                <el-form-item
                  prop="images"
                  :label="mainFields['images'].name ?? t('cms.content.images')"
                  :rules="
                    mainFields['images'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <image-list-upload
                    v-model="values.images"
                    :max-height="mainFields['images'].imageMaxHeight"
                    :max-width="mainFields['images'].imageMaxWidth"
                    :list-type="mainFields['images'].imageListType"
                    :disabled="disabled"
                  />
                </el-form-item>
              </el-col>
              <el-col
                v-if="mainFields['attachs'].show"
                :span="mainFields['attachs'].double ? 12 : 24"
              >
                <el-form-item
                  prop="attachs"
                  :label="mainFields['attachs'].name ?? t('cms.content.attachs')"
                  :rules="
                    mainFields['attachs'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <file-list-upload v-model="values.attachs" :disabled="disabled" />
                </el-form-item>
              </el-col>
              <template v-for="field in editorFields" :key="field.code">
                <el-col :span="field.double ? 12 : 24">
                  <el-form-item
                    :prop="`customs.${field.code}`"
                    :label="field.name"
                    :rules="
                      field.required
                        ? { required: true, message: () => t('common.required') }
                        : undefined
                    "
                  >
                    <template #label><label-tip :label="field.name" /></template>
                    <field-item v-model="values.customs[field.code]" :field="field" />
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-col>
          <!-- 编辑右区域 -->
          <el-col :span="6" >
            <el-tabs type="border-card" class="ml-5">
              <el-tab-pane :label="t('cms.content.setting')">
                <el-form-item
                  prop="channelId"
                  :label="rightFields['channel'].name ?? t('cms.content.channel')"
                  :rules="[
                    { required: true, message: () => t('common.required') },
                    {
                      validator: (rule, value, callback) => {
                        if (channelList.find((it) => it.id === value)?.children.length > 0) {
                          callback(t('cms.content.error.onlyLeafChannel'))
                          return
                        }
                        callback()
                      }
                    }
                  ]"
                >
                  <el-tree-select
                    v-model="values.channelId"
                    :data="channelList"
                    node-key="id"
                    :props="{ label: 'name' }"
                    :render-after-expand="false"
                    :default-expanded-keys="bean.channel?.nodeList.map((it) => it.id)"
                    class="w-full"
                    @change="
                      (value) => {
                        //重新触发获取栏目是否有工作流以及重新栏目的内容模型id和初始化内容模型字段信息
                        getChannelUseProcessDefinitionId()
                        contentModelId = flatChannelList.find(
                          (item) => item.id === value
                        )?.contentModelId
                        nextTick().then(() => {
                          initCustoms(values.customs)
                        })
                      }
                    "
                  />
                </el-form-item>

                <el-form-item
                  v-if="rightFields['releaseTime'].show"
                  prop="releaseTime"
                  :label="rightFields['releaseTime'].name ?? t('cms.content.releaseTime')"
                  :rules="
                    isEdit ? { required: true, message: () => t('common.required') } : undefined
                  "
                >
                  <el-date-picker
                    v-model="values.releaseTime"
                    type="datetime"
                    class="w-full"
                    @change="
                      (value: any) => {
                        if (value === null) values.releaseTime = undefined
                      }
                    "
                  />
                </el-form-item>
                <el-form-item
                  v-if="rightFields['contentMark'].show"
                  prop="contentMark"
                  :rules="
                    rightFields['contentMark'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label
                    ><label-tip
                      :label="rightFields['contentMark'].name ?? t('cms.content.contentMark')"
                      message="cms.content.contentMark"
                      help
                  /></template>
                  <el-select v-model="values.dictMark" class="w-full">
                    <el-option :label="t('common.selectText')" value="" />
                    <el-option
                      v-for="item in contentMarks"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="rightFields['block'].show"
                  prop="block"
                  :rules="
                    rightFields['block'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label
                    ><label-tip
                      :label="rightFields['block'].name ?? t('cms.content.block')"
                      message="cms.content.block"
                      help
                  /></template>
                  <el-select v-model="values.dictBlock" class="w-full">
                    <el-option :label="t('common.selectText')" value="" />
                    <el-option
                      v-for="item in contentBlocks"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="publishMultiChannelEnabled"
                  prop="subChannelIds"
                  :label="rightFields['subChannelIds'].name ?? t('cms.content.subChannelIds')"
                  :rules="rightFields['contentMark'].required
                      ? [{ required: true, message: () => t('common.required') },
                        {
                          validator: (rule, value, callback) => {
                          if (channelList.find((it) => it.id === value)?.children.length > 0) {
                            callback(t('cms.content.error.onlyLeafChannel'))
                            return
                          }
                          callback()
                        }}]
                      : [{
                        validator: (rule, value, callback) => {
                        if (channelList.find((it) => it.id === value)?.children.length > 0) {
                          callback(t('cms.content.error.onlyLeafChannel'))
                          return
                        }
                        callback()
                      }
                    }]
                    "
                >
                  <el-tree-select
                    v-model="values.subChannelIds"
                    :data="channelList"  
                    multiple
                    node-key="id"
                    :props="{ label: 'name' }"
                    :render-after-expand="false"
                    class="w-full"
                  />
                </el-form-item>
                <el-form-item
                  v-if="rightFields['topLevel'].show"
                  prop="topLevel"
                  :rules="
                    rightFields['topLevel'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label
                    ><label-tip
                      :label="rightFields['topLevel'].name ?? t('cms.content.topLevel')"
                      message="cms.content.topLevel"
                      help
                  /></template>
                  <el-input-number v-model="values.topLevel" :min="0" :max="999" />
                </el-form-item>

                <el-form-item
                  v-if="rightFields['source'].show"
                  prop="source"
                  :label="rightFields['source'].name ?? t('cms.content.source')"
                  :rules="
                    rightFields['source'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <el-autocomplete
                    v-model="values.source"
                    value-key="name"
                    :fetch-suggestions="
                      async (q: string, callback: any) => callback(await getSourceList(q))
                    "
                    class="w-full"
                    highlight-first-item
                    hide-loading
                    clearable
                    @keydown.enter.prevent
                  />
                </el-form-item>
                <el-form-item
                  prop="topStartTime"
                  :label="rightFields['topStartTime'].name ?? t('cms.content.topStartTime')"
                  :rules="
                    rightFields['topStartTime'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                  v-if="rightFields['topStartTime'].show"
                >
                  <el-date-picker v-model="values.topStartTime" type="datetime" class="w-full" />
                </el-form-item>
                <el-form-item
                  prop="topEndTime"
                  :label="rightFields['topEndTime'].name ?? t('cms.content.topEndTime')"
                  :rules="
                    rightFields['topEndTime'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                  v-if="rightFields['topEndTime'].show"
                >
                  <el-date-picker v-model="values.topEndTime" type="datetime" class="w-full" />
                </el-form-item>
                <el-form-item
                  prop="offlineTime"
                  :label="rightFields['offlineTime'].name ?? t('cms.content.offlineTime')"
                  :rules="
                    rightFields['offlineTime'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                  v-if="rightFields['offlineTime'].show"
                >
                  <el-date-picker v-model="values.offlineTime" type="datetime" class="w-full" />
                </el-form-item>
                <el-form-item
                  prop="onlineTime"
                  :label="rightFields['onlineTime'].name ?? t('cms.content.onlineTime')"
                  :rules="
                    rightFields['onlineTime'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                  v-if="rightFields['onlineTime'].show"
                >
                  <el-date-picker v-model="values.onlineTime" type="datetime" class="w-full" />
                </el-form-item>
                <el-form-item
                  v-if="rightFields['pcTpl'].show"
                  prop="pcTpl"
                  :label="rightFields['pcTpl'].name ?? t('cms.content.pcTpl')"
                  :rules="
                    rightFields['pcTpl'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label
                    ><label-tip
                      :label="rightFields['pcTpl'].name ?? t('cms.content.pcTpl')"
                      message="cms.content.pcTpl"
                      help
                  /></template>
                  <el-select v-model="values.pcTpl" class="w-full">
                    <el-option
                      v-for="item in contentPcTemplates"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-if="rightFields['h5Tpl'].show"
                  prop="h5Tpl"
                  :label="rightFields['h5Tpl'].name ?? t('cms.content.h5Tpl')"
                  :rules="
                    rightFields['h5Tpl'].required
                      ? { required: true, message: () => t('common.required') }
                      : undefined
                  "
                >
                  <template #label
                    ><label-tip
                      :label="rightFields['h5Tpl'].name ?? t('cms.content.h5Tpl')"
                      message="cms.content.h5Tpl"
                      help
                  /></template>
                  <el-select v-model="values.h5Tpl" class="w-full">
                    <el-option
                      v-for="item in contentH5Templates"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item v-if="values.pushTos?.length > 0" :label="t('cms.content.pushTos')">
                  <el-tooltip
                    v-for="item in values.pushTos"
                    :key="item.id"
                    :content="
                      (item.siteId != values.siteId ? `[${item.siteName}] ` : '') +
                      item.nodeNames.map((it: any) => it).join('>')
                    "
                    placement="top-start"
                  >
                    <el-input
                      :model-value="
                        (item.siteId != values.siteId ? `[${item.siteName}] ` : '') +
                        item.nodeNames.map((it: any) => it).join('>')
                      "
                      disabled
                    >
                      <template #append>{{ t(`cms.content.type.${item.createMode}`) }}</template>
                    </el-input>
                  </el-tooltip>
                </el-form-item>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </template>
      <template #footer-action="{ isEdit, handleSubmit }">
        <el-button
          :disabled="
            !checkPermi(['cms:content:submit', 'cms:content:update', 'cms:content:create'])
          "
          type="primary"
          native-type="submit"
          @click.prevent="() => handleSubmit()"
        >
          {{
            t(
              isEdit
                ? (channelUseProcessDefinitionId && values.editPublishContentToSubmit?'cms.content.op.submit':'cms.content.op.save')
                : channelUseProcessDefinitionId
                ? 'cms.content.op.submit'
                : 'cms.content.op.publish'
            )
          }}
        </el-button>
        <el-button
          :disabled="!checkPermi(['cms:content:update', 'cms:content:create'])"
          @click="() => handleSaveToDraft()"
          >{{ t('cms.content.op.saveToDraft') }}</el-button
        >
      </template>
    </dialog-form>
  </div>
</template>

<style lang="scss" scoped>
.label-top {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
    margin-bottom: 4px;
  }
}
//避免大图或者视频拉伸编辑器
.contentEditor {
  max-width: 100%;
}
</style>
